package com.home.generator.common.utils;

import com.home.generator.entity.ColumnEntity;
import com.home.generator.entity.TableEntity;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Description:
 * Created by 王大宸 on 2020-06-07 23:25
 * Created with IntelliJ IDEA.
 */
public class GeneratorUtils {
    private static final Logger logger = LoggerFactory.getLogger(GeneratorUtils.class);
    /**
     * 生成代码
     */
    public static void generatorCode(Map<String, String> table,
                                     List<Map<String, String>> columns,
                                     ZipOutputStream service) {
        // 配置信息
        Configuration config = getConfig();

        // 表信息
        TableEntity tableEntity = new TableEntity();
        tableEntity.setTableName(table.get("tableName"));
        tableEntity.setComments(table.get("tableComment"));

        // 表名转换成Java类名
        String className = tableToJava(tableEntity.getTableName(), config.getString("tablePrefix"));
        tableEntity.setClassName(className);
        tableEntity.setClassname(StringUtils.uncapitalize(className));

        // 列信息
        List<ColumnEntity> columnsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnEntity columnEntity = new ColumnEntity();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComments(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));

            // 列名转换成 Java 属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            // 列的数据类型，转换成 Java 类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType");
            columnEntity.setAttrType(attrType);

            // 是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
                tableEntity.setPk(columnEntity);
            }

            columnsList.add(columnEntity);
        }
        tableEntity.setColumns(columnsList);

        //  没主键，则第一个字段为主键
        if (tableEntity.getPk() == null) {
            tableEntity.setPk(tableEntity.getColumns().get(0));
        }

        // 设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        // 封装模板数据
        String mainModule = config.getString("mainModule");
        String appCode = config.getString("appCode");
        // 权限标识
        String permissionPrefix = getPermissionPrefix(appCode, mainModule, tableEntity.getClassname());
        // 菜单路径
        String menuUrl = getUrl(appCode, mainModule, permissionPrefix);
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableEntity.getTableName());
        map.put("comments", tableEntity.getComments());
        map.put("pk", tableEntity.getPk());
        map.put("className", tableEntity.getClassName());
        map.put("classname", tableEntity.getClassname());
        map.put("pathName", tableEntity.getClassname().toLowerCase());
        map.put("columns", tableEntity.getColumns());
        map.put("package", config.getString("package"));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        map.put("moduleName", mainModule);
        map.put("secondModuleName", toLowerCaseFirstOne(className));
        map.put("primaryKey", config.getString("primaryKey"));
        map.put("basePacker", config.getString("basePacker"));
        map.put("responsePacker", config.getString("responsePacker"));
        map.put("permsPrefix", permissionPrefix);
        map.put("menuUrl", menuUrl);
        map.put("parentId", IdUtil.getId());
        map.put("pageId", IdUtil.getId());
        map.put("addId", IdUtil.getId());
        map.put("editId", IdUtil.getId());
        map.put("delId", IdUtil.getId());
        map.put("seeId", IdUtil.getId());

        VelocityContext context = new VelocityContext(map);

        String type = config.getString("type");

        // 获取模板列表
        List<String> templates = getTemplates(type);
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                // 添加到 service
                service.putNextEntry(new ZipEntry(getFileName(template, tableEntity.getClassName(), config.getString("package"), menuUrl)));
                IOUtils.write(sw.toString(), service, "UTF-8");
                IOUtils.closeQuietly(sw);
                service.closeEntry();
            } catch (IOException e) {
                logger.error("Failed to render template，table name：" + tableEntity.getTableName(), e);
            }
        }
    }

    /**
     * 添加模板
     */
    public static List<String> getTemplates(String type) {
        List<String> templates = new ArrayList<String>();
        templates.add("templates/java/" + type + "/controller/controller.java.vm");
        templates.add("templates/java/" + type + "/service/service.java.vm");
        templates.add("templates/java/" + type + "/service/impl/serviceImpl.java.vm");
        templates.add("templates/java/" + type + "/entity/entity.java.vm");
        templates.add("templates/java/" + type + "/mapper/mapper.java.vm");

        templates.add("templates/java/" + type + "/xml/mapper.xml.vm");

        templates.add("templates/html/index.html.vm");
        templates.add("templates/html/add.html.vm");
        templates.add("templates/html/edit.html.vm");
        templates.add("templates/html/see.html.vm");

        templates.add("templates/js/index.js.vm");
        templates.add("templates/js/add.js.vm");
        templates.add("templates/js/edit.js.vm");
        templates.add("templates/sql/sql.vm");
        return templates;
    }


    /**
     * 列名转换成 Java 属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成 Java 类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            logger.error("获取配置失败", e);
            return null;
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String menuUrl) {
        String packagePath = "home-admin" + File.separator + "java" + File.separator;
        String resourcesPath = "home-admin" + File.separator + "resources" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }
        /* java  */
        if (template.contains("service.java.vm")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }
        if (template.contains("serviceImpl.java.vm")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }
        if (template.contains("mapper.java.vm")) {
            return packagePath + "mapper" + File.separator + className + "Mapper.java";
        }
        if (template.contains("entity.java.vm")) {
            return packagePath + "entity" + File.separator + className + ".java";
        }
        if (template.contains("controller.java.vm")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }
        /* mapper */
        if (template.contains("mapper.xml.vm")) {
            return resourcesPath + "mapper" + File.separator + className + "Mapper.xml";
        }
        /* html */
        if (template.contains("index.html.vm")) {
            return resourcesPath + "html" + File.separator + menuUrl + File.separator + "index.html";
        }
        if (template.contains("edit.html.vm")) {
            return resourcesPath + "html" + File.separator + menuUrl + File.separator + "edit.html";
        }
        if (template.contains("add.html.vm")) {
            return resourcesPath + "html" + File.separator + menuUrl + File.separator + "add.html";
        }
        if (template.contains("see.html.vm")) {
            return resourcesPath + "html" + File.separator + menuUrl + File.separator + "see.html";
        }
        /* js */
        if (template.contains("index.js.vm")) {
            return resourcesPath + "js" + File.separator + menuUrl + File.separator + "index.js";
        }
        if (template.contains("add.js.vm")) {
            return resourcesPath + "js" + File.separator + menuUrl + File.separator + "add.js";
        }
        if (template.contains("edit.js.vm")) {
            return resourcesPath + "js" + File.separator + menuUrl + File.separator + "edit.js";
        }
        if (template.contains("sql.vm")) {
            return resourcesPath + "sql" + File.separator + className + "Menu.sql";
        }
        return null;
    }

    /**
     * 首字母转小写
     */
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        } else {
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }

    /***
     * 功能说明：获取权限前缀
     *
     * @author 王大宸
     * @date 2020/11/12 0:22
     * @param appCode         应用编码
     * @param moduleName      模块名称
     * @param clazzName       java 类名
     * @return java.lang.String
     */
    public static String getPermissionPrefix(String appCode, String moduleName, String clazzName) {
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotEmpty(appCode) && !appCode.equals(moduleName)) {
            stringBuilder.append(appCode).append(":");
        }
        if (StringUtils.isNotEmpty(moduleName) && !appCode.equals(moduleName)) {
            stringBuilder.append(moduleName).append(":");
        }
        if (appCode.equals(moduleName)) {
            stringBuilder.append(moduleName).append(":");
        }
        for (int i = 0; i < clazzName.length(); i++) {
            char c = clazzName.charAt(i);
            if (Character.isUpperCase(c)) {
                stringBuilder.append(":").append(Character.toLowerCase(c));
                continue;
            }
            stringBuilder.append(c);
        }
        return stringBuilder.toString();
    }

    public static String getUrl(String appCode, String moduleName, String permissionPrefix) {
        if (StringUtils.isNotEmpty(appCode) && !appCode.equals(moduleName)) {
            return permissionPrefix.replace(appCode + ":", "").replaceAll(":", "/");
        } else {
            return permissionPrefix.replaceAll(":", "/");
        }
    }

}
